import { IAppDEUIAction } from '@ibiz/model-core';
import {
  IUILogicParams,
  IUIActionResult,
  UIActionProviderBase,
} from '@ibiz-template/runtime';

/**
 * 打印
 *
 * @export
 * @class PrintUIActionProvider
 * @extends {UIActionProviderBase}
 */
export class PrintUIActionProvider extends UIActionProviderBase {
  /**
   * 执行界面行为
   *
   * @param {IAppDEUIAction} action
   * @param {IUILogicParams} args
   * @return {*}  {Promise<IUIActionResult>}
   * @memberof PrintUIActionProvider
   */
  async execAction(
    action: IAppDEUIAction,
    args: IUILogicParams,
  ): Promise<IUIActionResult> {
    const { data, context, params } = args;
    const { resultParams } = await this.handleParams(
      action,
      context, data, params
    );
    let innerHTML = '';
    if (resultParams.queryselector) {
      const html = document.querySelector(resultParams.queryselector);
      if (html) innerHTML = html.innerHTML;
    } else if (resultParams.dataitemname) {
      innerHTML = data[0]?.[resultParams.dataitemname]
    }
    if (!innerHTML || typeof innerHTML !== 'string') {
      ibiz.message.warning('未指定打印目标');
      return { cancel: true };
    };
    this.printHtml(innerHTML);
    return {};
  }

  /**
   * 打印html内容
   *
   * @private
   * @param {string} innerHTML
   * @memberof PrintUIActionProvider
   */
  private printHtml(innerHTML: string): void {
    // 创建一个隐藏的 iframe
    const iframe = document.createElement('iframe');
    iframe.style.position = 'fixed';
    iframe.style.right = '0';
    iframe.style.bottom = '0';
    iframe.style.width = '0';
    iframe.style.height = '0';
    iframe.style.border = '0';
    // 将 iframe 添加到文档中
    document.body.appendChild(iframe);
    // 获取 iframe 的文档对象
    const iframeDocument = iframe.contentDocument || iframe.contentWindow!.document;
    // 写入 iframe
    iframeDocument.write(innerHTML);
    // 关闭文档流，确保内容加载完成
    iframeDocument.close();
    // 调用打印功能
    iframe.contentWindow!.print();
    // 打印完成后移除 iframe
    iframe.contentWindow!.onafterprint = () => {
      document.body.removeChild(iframe);
    };
  }
}
